package com.gadgets.framework.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-09-19
 *
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
public class DigestUtil {

    private static final Logger logger = LoggerFactory.getLogger(DigestUtil.class);

    public static final char[] HEX_DIGITS ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

    /**
     * SHA2-512加密算法
     * @param msg   原文
     * @return      密文
     */
    public static String digestBySHA2_512(String msg){
        try {
            byte[] btInput = msg.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("SHA-512");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
                str[k++] = HEX_DIGITS[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            logger.error(StringUtils.formatExceptionStack(e));
            return null;
        }
    }

}
